package de.unistuttgart.iaas.interaction.mail;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Properties;


import java.sql.*;

import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.RollingFileAppender;
import com.eaio.uuid.UUID;

import de.unistuttgart.iaas.interaction.mail.database.MySQLAccess;
import de.unistuttgart.iaas.interaction.mail.util.ConfigFileHandler;
import de.unistuttgart.iaas.interaction.mail.util.LoggingFileHandler;

/**
 * This class is for register. 
 * @author Lina
 *
 */
@SuppressWarnings("restriction")
public class Register {
	
	private static Logger logger = Logger.getLogger(Register.class);

	/**
	 * The function of this method is register for new user, handles all mails with mail_class=REGISTER and mail_state=NEW.
	 */
	public static void register(String configurationData)
    {

		ConfigFileHandler config = new ConfigFileHandler(configurationData);
		LoggingFileHandler logFileHandler = new LoggingFileHandler(configurationData);
		
		Properties properties = new Properties();
		properties.setProperty("log4j.rootLogger", logFileHandler.getMailLogLevel()+", R");
		properties.setProperty("log4j.appender.R", logFileHandler.getMailAppender());
		properties.setProperty("log4j.appender.R.File", logFileHandler.getRegisterLogFilePath());
		properties.setProperty("log4j.appender.R.MaxFileSize", logFileHandler.getMailLogFileSize() );
		properties.setProperty("log4j.appender.R.MaxBackupIndex", logFileHandler.getMailMaxBackupIndex());
		properties.setProperty("log4j.appender.R.layout", logFileHandler.getMailLayout());
		properties.setProperty("log4j.appender.R.layout.ConversionPattern", logFileHandler.getMailPattern());
		PropertyConfigurator.configure( properties );
		logger.info("--------------------RegisterService---------------------");
		
		MySQLAccess dao = new MySQLAccess();
	    	   	
   	    try
   	    {
   			Connection conn = dao.connDataBase(config);
   			
   			Statement statement = conn.createStatement();
   			ResultSet rs = statement.executeQuery("select mail_id, mail_from, mail_from_username from maildb.mailbox where mail_class=" +
   					"'REGISTER' and mail_state='NEW'");
   			
   			if(rs.next())
   			{
   				String mail_id = rs.getString("mail_id");
   				String mail_from = rs.getString("mail_from");
   				String mail_from_username = rs.getString("mail_from_username");
   				ResultSet resultset = statement.executeQuery("select mailaddress from maildb.mailregister where mailaddress='"+mail_from+"'");
   				if(!resultset.next())
   				{
					PreparedStatement preStatementRegister= conn.prepareStatement("insert into maildb.mailregister (mailaddress,username) values(?,?)");
					preStatementRegister.setString(1,mail_from);
					preStatementRegister.setString(2,mail_from_username);
					preStatementRegister.executeUpdate();
					preStatementRegister.close();
 					statement.executeUpdate("update maildb.mailbox set mail_state='FINISHED' where mail_id='"+mail_id+"'");
 					
 					//generate an internal request to confirm the register.
 		 			PreparedStatement preStatement = conn.prepareStatement("insert into maildb."+ config.getTable_sentmails()+" values(?,?,?,?,?,?,?,?,?,'Request',?)");
 		 			UUID u = new UUID();
 		 			String subject = "You have been registered.";
 		 			String message ="\n your register is successful. Now you can call our mail service.\n";
 		 			Calendar cal = Calendar.getInstance();
 		 			DateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  			
 		 			String sendTime = df.format(cal.getTime());
 		 			String response = "no";
 		 			String responseType = "";
 		 			String newtime=null;

 		 			preStatement.setString(1, u.toString());
 		 			preStatement.setString(2, mail_from);
 		 			preStatement.setString(3, config.getMailAddress());
 		 			preStatement.setString(4, subject);
 		 			preStatement.setString(5, message);
 		 			preStatement.setString(6, sendTime);
 		 			preStatement.setString(7, response);
 		 			preStatement.setString(8, responseType);		 			
 		 			preStatement.setString(9, newtime);		
 		 			preStatement.setString(10, "NEW");
 		 			preStatement.executeUpdate();
 		 			preStatement.close();
 					
 		 			logger.info("New user:\n Address: "+ mail_from+"\n Username: "+ mail_from_username);
 					System.out.println("New user:\n Address: "+ mail_from+"\n Username: "+ mail_from_username);
 					
   				}else{
   					logger.info("The user("+ mail_from+") is already registered!");
   					System.out.println("The user("+ mail_from+") is already registered!");
   				}

   			}
	    		
    	}catch(Exception e)
    	{
    		
    		System.out.println("Error by Register!Please restart the Server.");
    	}
    }

}
